package com.itlong.cloud.controller.tm;


import com.alibaba.da.coin.ide.spi.meta.ExecuteCode;
import com.alibaba.da.coin.ide.spi.meta.ResultType;
import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.VO.app.AppElevatorFloorSimpleVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.enumerate.CallElevatorSourceTypeEnum;
import com.itlong.cloud.enumerate.CloudElevatorCallTypeEnum;
import com.itlong.cloud.enumerate.CloudElevatorSourceEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * <desc>
 *     新版APP天猫精灵版块控制器 供展会使用demo
 * </desc>
 *
 * @create  2019/10/20
 */
@RestController
@RequestMapping("/tm")
public class TmController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(TmController.class);

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    private RedisService redisService;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    /**
     *  <desc>
     *      天猫精灵获取code
     *  </desc>
     *
     * @create 2019/10/20
     * @author Qiang.S
     */
    @RequestMapping(path = "/tmGetCode")
    @ResponseBody
    @UnParamEncrypt
    @UnAuthAccessRequired
    public Object tmGetCode(HttpServletRequest request, HttpServletResponse response){

        //LOG.info("【小米获取code】");
        //LOG.info(request.getParameterMap().toString());
        JSONObject json = new JSONObject();
        json.put("code","2YotnFZFEjr1zCsicMWpAA");
        json.put("state","example");
        json.put("expires_in",3600);
        json.put("refresh_token","tGzv3JOkF0XG5Qx2TlKWIA");
        json.put("example_parameter","example_value");
        response.addHeader("Cache-Control","no-store");
        response.addHeader("Pragma","no-store");
        return json.toJSONString();
    }

    /**
     *  <desc>
     *      天猫精灵登录
     *  </desc>
     *
     * @create 2019/10/20
     * @author Qiang.S
     */
    @RequestMapping(path = "/tmLogin")
    @ResponseBody
    @UnParamEncrypt
    @UnAuthAccessRequired
    public Object tmLogin(HttpServletRequest request){
        try {
            //LOG.info("【天猫精灵登录请求进入】");
            //LOG.info(request.getParameterMap());
            JSONObject json = new JSONObject();
            json.put("access_token","2YotnFZFEjr1zCsicMWpAA");
            json.put("expires_in",17600000);
            json.put("refresh_token","tGzv3JOkF0XG5Qx2TlKWIA");
            return json.toJSONString();
        }catch (Exception e){
            throw new DataAccessException("【天猫精灵_tmLogin】天猫精灵登录",e);
        }
    }

    /**
     * <desc>
     *      天猫精灵呼梯。
     * <desc/>
     *
     * @param
     * @return
     * @author Qiang.S
     * @create 2019/10/20
     */
    @RequestMapping(path = "/callElevator")
    @ResponseBody
    @UnParamEncrypt
    @UnAuthAccessRequired
    public ResultModel<TaskResult> callElevator(HttpServletRequest request, @RequestBody()String taskQuery) throws IOException {
        try {
            ResultModel<TaskResult> resultModel = new ResultModel<>();
            TaskResult taskResult = new TaskResult();
            String token = request.getHeader("token");
            if(!token.equals("itlong")){
                taskResult.setReply("不合法语音，拒绝服务");
                taskResult.setResultType(ResultType.RESULT);
                resultModel.setReturnValue(taskResult);
                //LOG.info(resultModel.toString());
                return resultModel;
            }
            String deviceUnique = request.getHeader("deviceUnique");
            String fromFloor = request.getHeader("fromFloor");
            String toFloor = request.getHeader("toFloor");
            String deviceId = Integer.parseInt(deviceUnique.substring(9,13))+"";

            //LOG.info("Ttoken:"+token);
            //LOG.info("入参:" + taskQuery);
            TaskQuery query = MetaFormat.parseToQuery(taskQuery);
            //LOG.info(query.toString());
            Map<String, Object> input = JsonUtil.JsonToMap(taskQuery);
            JSONArray jsonArray = (JSONArray)input.get("slotEntities");
            String elevator = null;
            String floor = null;
            //47313楼层    47314电梯
//        if (jsonArray != null || jsonArray.size() > 0) {
//            for (Object jsonObject : jsonArray) {
//                JSONObject json = (JSONObject) jsonObject;
//                String intentParameterId = json.get("intentParameterId").toString();
//                if ("47313".equals(intentParameterId)) {
//                    elevator = json.getString("standardValue");
//                }
//                if ("47314".equals(intentParameterId)) {
//                    floor = json.getString("standardValue");
//                }
//            }
//            if (redisService.get("tmCallElevator") == null || "0".equals(redisService.get("tmCallElevator"))) {//第一次
//                taskResult.setReply("请告诉我几号电梯");
//                taskResult.setResultType(ResultType.CONFIRM);
//                redisService.set("tmCallElevator", "1");
//            }else if ("1".equals(redisService.get("tmCallElevator"))) {//询问电梯编号之后
//                if (StringUtils.isBlank(elevator)) {
//                    taskResult.setReply("请告诉我几号电梯");
//                    taskResult.setResultType(ResultType.CONFIRM);
//                } else {
//                    redisService.set("tmCallElevator",15L, "2");
//                    redisService.set("tmElevator",15L, elevator);
//                    taskResult.setReply("请告诉我几楼");
//                    taskResult.setResultType(ResultType.CONFIRM);
//                }
//            }else if ("2".equals(redisService.get("tmCallElevator"))) {//询问过楼层后
//                if (StringUtils.isBlank(floor)) {
//                    taskResult.setReply("请告诉我几楼");
//                    taskResult.setResultType(ResultType.CONFIRM);
//                }else {
            taskResult.setReply("已为您呼叫"+ deviceId+"号电梯");
            taskResult.setResultType(ResultType.RESULT);
//               redisService.del("tmElevator");
//               redisService.set("tmCallElevator",15L, "0");
//                }
//            }
//        }
//        else {
//            redisService.set("tmCallElevator", "1");
//            taskResult.setReply("请告诉我几号电梯");
//            taskResult.setResultType(ResultType.CONFIRM);
//        }
            //取真实楼层
            AppElevatorFloorSimpleVO simpleVO = iAppHomeServiceClient.getRealFloorInfo(deviceUnique, fromFloor, toFloor);
            //调用IOT呼梯
            iAppDeviceServiceClient.cloudElevatorCall(
                    deviceUnique,
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    simpleVO.getRealFrom(),simpleVO.getRealTo(),null, CloudElevatorCallTypeEnum.OUT.getType(),null,
                    CallElevatorSourceTypeEnum.APP.getType(),null, LogicIdUtil.randomNum(),null, null, null, null, "");
            taskResult.setExecuteCode(ExecuteCode.SUCCESS);

            resultModel.setReturnValue(taskResult);
            //LOG.info(resultModel.toString());
            return resultModel;
        } catch (Exception e) {
            throw new DataAccessException("【APP_天猫精灵服务】天猫精灵呼梯失败",e);
        }
    }

}
